define(['app', 'pagination'], function(app) {
    'use strict';
    app.controller('QyApp', function($scope, dataFactoryCRM, $q ,$routeParams,$rootScope) {
         $scope.qy_app = '';
    	 $scope.yqList = '';
         $scope.sales  = '';
    	 $scope.productList = '';
    	 $scope.add = {};
         $scope.qy_code = "";

    	//默认分页
       	$scope.QyAppPage = { pageAll: 1, pageNow: 1, pageSize: 20, k: 3 };
    	//默认检索条件
        $scope.search = { app_name: '', qy_name: '', app_admin: ''};

        $scope.$watch('$viewContentLoading',function(event, viewConfig){ 
            $scope.qy_code = "";
        });
       
        //归属企业号数据
        if($scope.yqList == '' || $scope.productList == ''){
        	$scope.busy = dataFactoryCRM.getDataByAPI('QyApp/productData').then(function(data) {
	            $scope.yqList = data.qy;
                $scope.qy_app = data.qy_app;
	            $scope.productList = data.produt;
                $scope.search.qy_name = data.cookie_qy_name;
                $scope.QyAppList($scope.qy_app);
	        });
        }

    	//列表页
    	$scope.QyAppList = function() {
    	 	var listParam = $scope.search;
            listParam['psize'] = $scope.QyAppPage.pageSize;
            listParam['p'] = $scope.QyAppPage.pageNow;
            if($scope.qy_app!=""){
                if($routeParams.qy_code && $scope.qy_code==""){
                    $scope.qy_code = $routeParams.qy_code;
                    $scope.search.qy_name = $scope.qy_code;
                }
            }
            var _url = 'QyApp/index?' + $.param(listParam);
            dataFactoryCRM.getDataByAPI(_url)
                .then(function(data) {
                    if(data.rcode == 1){
            			$scope.listEmpty = false;
                        $scope.listData  = true;
                		$scope.qy_app_list = data.list;
                        $scope.QyAppPage.pageSize = data.psize;
                        $scope.QyAppPage.pageAll = data.pall;
                        $scope.QyAppPage.pageNow = data.p;
                	}else{
                        $scope.listData  = false;
                		$scope.listEmpty = true;
                	}
            })
    	}
    	 //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function() {
            $scope.QyAppList();
        });
            //特殊处理semantic dropdown的反向绑定缺陷
        $scope.$watch('search.qy_name', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='search.qy_name']").dropdown('set selected', newValue);
            });
        }, true);
        
        //添加栏目
        $scope.addApp = function(){
        	$("#frm-add").form('clear');
        	$('.ui.add').modal({
                observeChanges: true,
                onApprove: function() {
                    if($('#frm-add').form('is valid')){
                        dataFactoryCRM.postDataByAPI("QyApp/add_app",$scope.add)
			                .then(function(data) {
			                	if (data.rcode == 1) 
			                        $('.ui.modal2').modal('show');
			                    else 
			                    	$('.ui.modal3').modal('show');

			                    $scope.Msg = data.msg;
			                    setTimeout(function() {
                                    $('.time').modal('hide');
                                     $scope.QyAppList();
                                }, 1000);    
			            })
                    }else{ 
                        return false;
                    }
                }
            }).modal('show');       
        }
        //设置管理员
        $scope.addAdmin = function(appId){
        	
            $("#frm-admin").form('reset');
            $("#frm-admin a").remove(".ui.label.transition.visible");
            $("#frm-admin div").remove(".menu.transition .item");
            $("#hideAppId").val(appId);

        	$('.ui.add_admin').modal({
                observeChanges: true,
                autofocus:false,
                onApprove: function() {
                	var add_admin = $("#add_admin").val();
                    dataFactoryCRM.getDataByAPI("QyApp/add_admin?customer_id=" + add_admin + '&app_id='+appId)
		                .then(function(data) {
		                	if (data.rcode == 1) 
		                        $('.ui.modal2').modal('show');
		                    else 
		                    	$('.ui.modal3').modal('show');

		                    $scope.Msg = data.msg;
		                    setTimeout(function() {
                                $('.time').modal('hide');
                                 $scope.QyAppList();
                            }, 3000);    
		            })
                }
            }).modal('show'); 
             dataFactoryCRM.getDataByAPI("QyApp/sales_peron?app_id="+appId)
                    .then(function(data) {
                        if(data.rcode == 1){
                            if(data.user){
                                $scope.sales = data.user;
                                $scope.userList = $scope.sales ;
                                for(var i=0;i<$scope.sales.length;i++)
                                {   
                                    $("#frm-admin .ui.dropdown .search ").before("<a class='ui label transition visible' data-value='"+$scope.sales[i].user_id+"' style='display: inline-block !important;'>"+$scope.sales[i].nickname +"("+ $scope.sales[i].role_name+" ,"+$scope.sales[i].sector_name+" )"+"<i class='delete icon'></i></a>");
                                }   
                            }
                            if(data.selected_admin){
                                $scope.selected_admin = data.selected_admin;
                                setTimeout(function() {
                                    angular.element("#frm-admin select[name='add_admin_name']").dropdown('set selected',$scope.selected_admin);
                                });
                            }
                        }else{
                             $scope.userList = [];
                        }
                }) 
        }
        //监听select事件
        $('#frm-admin').bind('input propertychange', function() { 
            var appId = $("#hideAppId").val();
            var text = $("#frm-admin .sizer").text();
            if(text !=""){
                dataFactoryCRM.postDataByAPI("QyApp/sales_peron?nickname="+text+'&app_id='+appId,{user:$scope.userList})
                    .then(function(data) {
                        if(data.rcode == 1){
                            $scope.sales = data.user;
                            if($scope.sales.length > 0 && $scope.userList.length > 0){
                                $.merge($scope.userList,$scope.sales); 
                            }else{                           
                                $scope.userList = $scope.sales;
                            }
                        }
                        var selectedId = $("#add_admin").val();
                        setTimeout(function() {
                            angular.element("#frm-admin select[name='add_admin_name']").dropdown('set selected',selectedId);
                        });
                }) 
            }
        });
        $('#frm-admin .menu').on("click",function(){
            $('#frm-admin .ui.dropdown').dropdown("hide");
        })
        //设置套餐
        $scope.addPackage = function(qyCode,appId){
        	$("#frm-package").form('clear');
            $("#frm-package a").remove(".ui.label.transition.visible");
            $("#frm-package div").remove(".menu.transition .item");

        	$('.ui.package').modal({
                observeChanges: true,
                autofocus:false,
                onApprove: function() {
                    var packages = $("#packages").val();
                    if($('#frm-package').form('is valid') ){
                        dataFactoryCRM.postDataByAPI("QyApp/add_package?packages=" + packages + '&app_id='+appId)
			                .then(function(data) {
			                	if (data.rcode == 1) 
			                        $('.ui.modal2').modal('show');
			                    else 
			                    	$('.ui.modal3').modal('show');

			                    $scope.Msg = data.msg;
			                    setTimeout(function() {
                                    $('.time').modal('hide');
                                     $scope.QyAppList();
                                }, 3000);    
			            })
                    }else{ 
                    	return false;
                    }
                }
            }).modal('show'); 
            dataFactoryCRM.getDataByAPI("QyApp/product_package?qy_code=" + qyCode+ '&app_id='+appId)
                .then(function(data) {
                	if(data.rcode == 1){
                        if(data.product_package){
                            $scope.productList = data.product_package;
                            for(var i=0;i<$scope.productList.length;i++)
                            {   
                                if($scope.productList[i].my_app){
                                    $("#frm-package .ui.dropdown .search ").before("<a class='ui label transition visible' data-value='"+$scope.productList[i].package_code +"' style='display: inline-block !important;'>"+$scope.productList[i].name+"<i class='delete icon'></i></a>");
                                    $("#frm-package .ui.dropdown .default.text").text("");
                                }
                            }
                        }
                        if(data.selected_app){
                           $scope.selected_app = data.selected_app;
                           setTimeout(function() {
                                angular.element("#frm-package select[name='packages']").dropdown('set selected', $scope.selected_app);
                            });
                        }
                       
                	}	
            })      
        }
        //查看详情
        $scope.viewDetails = function(){
        	$scope.details = this.vlist;

        	dataFactoryCRM.getDataByAPI("QyApp/view_details?qy_app_id="+$scope.details.qy_app_id)
                .then(function(data) {
                	$scope.package_data = data.package_name;
            })
        	$('.ui.view_details').modal('show'); 
        } 
    })
})